# coding=utf-8
import arcpy
import math
import json

path = r'D:\WorkData\20250712四川河流\0812'
arcpy.env.workspace = path
arcpy.env.overwriteOutput = True
spatial_ref = arcpy.SpatialReference(4326)
riv = r'D:\WorkData\20250712四川河流\0812\rivs.shp'.decode('utf-8')
lp = r'D:\WorkData\20250712四川河流\0812\p.shp'.decode('utf-8')

cs1 = arcpy.da.SearchCursor(lp,['SHAPE@','SHAPE@x','SHAPE@y','name','dis','n_riv_name','n_riv_id','n_riv_lv','FID','rivid'])
j = 0
for row1 in cs1:
    n_riv_id = row1[6]
    expression = "rivId = '{}'".format(n_riv_id)

    cs2 = arcpy.da.SearchCursor(riv, ['SHAPE@JSON', 'SHAPE@', 'rivid'], where_clause=expression)
    pointList = json.loads([row2[0] for row2 in cs2][0])['paths'][0]

    cs2.reset()

    dis = 1
    insIndex = 0
    cs3 = arcpy.da.SearchCursor(riv, ['SHAPE@', 'SHAPE@X', 'SHAPE@Y', 'rivid'], where_clause=expression, explode_to_points=True)
    i = 0
    for row3 in cs3:
        if (row1[0].distanceTo(row3[0]) < dis):
            insIndex = i
            dis = row1[0].distanceTo(row3[0])
        i += 1
    cs3.reset()

    # print j, row1[3], row1[5], row1[6],insIndex
    x1 = pointList[insIndex][0]
    y1 = pointList[insIndex][1]
    x2 = pointList[insIndex - 1][0]
    y2 = pointList[insIndex - 1][1]

    segmentLength = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
    pointX = row1[1]
    pointY = row1[2]
    pToSegmentSP = math.sqrt((pointX - x2) ** 2 + (pointY - y2) ** 2)
    if (segmentLength > pToSegmentSP):
        pointList.insert(insIndex, [pointX,pointY])
    else:
        pointList.insert(insIndex + 1, [pointX,pointY])

    print pointList

    with arcpy.da.UpdateCursor(riv, 'SHAPE@JSON', where_clause=expression) as yb:
        for row in yb:
            geoJson = json.loads(row[0])
            geoJson['paths'] = [pointList]
            row[0] = json.dumps(geoJson)
            yb.updateRow(row)
    with arcpy.da.UpdateCursor(riv, 'SHAPE@JSON', where_clause=expression) as yb:
        for row in yb:
            print row[0]
    j += 1

